<?php

namespace App\Http\Controllers\Admin\Transport;

use App\Exceptions\AppException;
use App\Http\Controllers\Controller;
use App\Models\cainiao\NotifyModel;
use App\Models\lazada\BigBagModel;
use App\Models\OrderModel;
use App\Models\service\AbnormalModel;
use App\Models\service\CompensateModel;
use App\Models\service\ProblemModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderBig extends Controller
{

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $keyword = $request->input('sn', '');
        $customer_id = $request->input('customer_id', '');
//        $goods_attr = $request->input('goods_attr', '');
        $des_country_id = $request->input('des_country_name', '');
//        $clearance_mode = $request->input('clearance_mode', '');
//        $customer_type_id = $request->input('customer_type', '');
//        $is_clearance = $request->input('is_clearance', '');
        $status = $request->input('status', '');
        $place_id = $request->input('place_id', '');
//        $warehouse_id = $request->input('warehouse_id', '');
        $start_time = $request->input('startTime', '');
        $end_time = $request->input('endTime', '');

        $query = OrderModel::query()
            ->whereHas('customer', function($query){
                $query->where('is_big', 1);
            })->with(['customer', 'take_order']);

        if($keyword) {
            $query->where('sn', 'like', "%{$keyword}%");
        }

        if($customer_id){
            $query->where('customer_id', $customer_id);
        }

//        if($customer_type_id) {
//            $query->where('customer_type_id', $customer_type_id);
//        }
//
//        if($goods_attr){
//            $query->where('goods_attr', $goods_attr);
//        }

        if($des_country_id){
            $query->where('destination', $des_country_id);
        }


        if($status){
            $query->where('status', $status);
        }

        if($place_id){
            $query->where('place_id', $place_id);
        }

        if($start_time && $end_time){
            $query->whereBetween('created_at', [$start_time, $end_time]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            $res = [
                'id' => $item->id,
                'sn' => $item->sn,
                'customer_name' => $item->customer->name ?? '',
                'take_order_sn' => $item->take_order->sn ?? '',
                'goods_label' => $item->goods_label,
                'big_pkgs' => $item->big_pkgs,
                'storage_weight' => $item->storage_weight,
                'storage_volume' => '',
                'des_country_name' => $item->airport->country_name ?? '',
                'status' => $item->status,
                'status_text' => OrderModel::STATUS_MAPS[$item->status] ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'small_pkgs' => $item->small_pkgs,
                'created_at' => $item->created_at->toDateTimeString(),
//                'warehouse_name' => $item->created_admin->staff->warehouse->name ?? '',
                'storage_remark' => $item->storage_remark
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function detail(Request $request) {
        $id = $request->input('id');
        $order = OrderModel::with(['customer', 'take_order'])->find($id);
        if(!$order){
            return $this->error('订单不存在');
        }

        $base_info = [
            'id' => $order->id,
            'customer_name' => $order->customer->name ?? '',
            'order_sn' => $order->sn,
            'take_order_sn' => $order->take_order->sn ?? '',
            'status_text' => OrderModel::STATUS_MAPS[$order->status] ?? '',
            'storage_time' => $order->storage_time,
            'big_pkgs' => $order->big_pkgs,
            'small_pkgs' => $order->small_pkgs,
            'goods_label' => $order->goods_label,
            'place_name' => $order->place->name ?? '',
            'storage_remark' => $order->storage_remark,
            'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
            'storage_weight' => $order->storage_weight,
            'destination' => $order->destination,
        ];

        $notify = BigBagModel::where('order_id', $id)->get();
        if($notify){
            $big_list = $notify->map(function($item) use ($order) {
                return [
                    'id' => $item->id,
                    'bigBagID' => $item->bigBagID,
                    'destination' => $item->destination,
                    'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->cargoType] ?? '',
                    'grossWeight' => round($item->bigBagWeight / 1000, 2),
                    'parcelQty' => $item->parcelQty,
                ];
            });

            $base_info['big_list'] = $big_list;
        }else{
            $base_info['big_list'] = [];
        }

        $return['base_info'] = $base_info;


        return $this->success($return);
    }


    public function cancel(Request $request) {
        $id = $request->input('id',  '');
        $big_ids = $request->input('big_ids', []);

        $order = OrderModel::find($id);
        if(!$order){
            return $this->error('入仓单不存在');
        }

        $bigs = BigBagModel::whereIn('id', $big_ids)->get();

        if(!$bigs){
            return $this->error('大包不存在');
        }

        DB::beginTransaction();
        try{
            $small_pkgs = $bigs->sum('parcelQty') ?? 0;
            $storage_weight = $bigs->sum('bigBagWeight') ?? 0;
            $storage_weight = round($storage_weight / 1000, 2);
            $order->big_pkgs = $order->big_pkgs - count($bigs);
            $order->small_pkgs = $order->small_pkgs - $small_pkgs;
            $order->storage_weight = $order->storage_weight - $storage_weight;
            $order->save();

            BigBagModel::whereIn('id', $big_ids)->update([
                'order_id' => 0,
            ]);

            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


    public function get_big_bag_ids(Request $request) {
        $id = $request->input('id');

        $order = OrderModel::find($id);
        if(!$order){
            return $this->error('订单不存在');
        }

        $notify = BigBagModel::where('order_id', $id)->get();

        $list = $notify->map(function($item) {
            return [
                'id' => $item->id,
                'bigBagID' => $item->bigBagID,
                'length' => $item->length,
                'width' => $item->width,
                'height' => $item->height,
            ];
        });

        return $this->success(['list' => $list]);
    }

    public function size_enter(Request $request) {
        $data = $request->input('data', []);
        if(!$data){
            return $this->error('数据不能为空');
        }

        DB::beginTransaction();
        try{
            foreach ($data as $item){
                NotifyModel::where('id', $item['id'])->update([
                    'length' => $item['length'],
                    'width' => $item['width'],
                    'height' => $item['height'],
                ]);
            }

            DB::commit();

        }catch (AppException $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

}
